package com.cungmua.app.adapter;

import android.content.Context;
import android.graphics.Paint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.cungmua.app.R;
import com.cungmua.app.handler.CartItemSelectedHandler;
import com.cungmua.app.model.CartItem;
import com.cungmua.app.model.DealDetails;
import com.cungmua.app.model.SKU;
import com.cungmua.app.utils.AppUtils;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by kelvin.nguyen on 6/25/14.
 */
public class SkuListAdapter extends BaseAdapter {
    private final LayoutInflater inflater;
    private final CartItemSelectedHandler handler;
    private final int productId;
    private final List<CartItem> selectedItems;
    private List<SKU> dataSource;
    private final Context context;
    private DealDetails details;

    public SkuListAdapter(int productId, Context context, DealDetails details,
                          CartItemSelectedHandler handler, List<CartItem> selectedItems) {
        this.productId = productId;
        this.context = context;
        this.dataSource = new ArrayList<SKU>();
        this.inflater = LayoutInflater.from(context);
        this.handler = handler;
        this.selectedItems = selectedItems;
        this.details = details;
    }

    public void setDataSource(List<SKU> source) {
        this.dataSource = source;
        notifyDataSetChanged();
    }

    public List<SKU> getDataSource() {
        return dataSource;
    }

    @Override
    public int getCount() {
        return dataSource.size();
    }

    @Override
    public SKU getItem(int i) {
        return dataSource.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    private class ViewHolder {
        public TextView txtSkuName;
        public ImageView imgSku,btnChayhang;
        public Spinner spnQuantity;
        public TextView txtPrice;
        public TextView txtMarketPrice;
    }

    @Override
    public View getView(int i, View convertView, ViewGroup parent) {
        final SKU sku = dataSource.get(i);
        ViewHolder holder;

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.sku_item, parent, false);
            holder = new ViewHolder();

            holder.imgSku = (ImageView) convertView.findViewById(R.id.imgSku);
            holder.btnChayhang = (ImageView) convertView.findViewById(R.id.btnChayhang);
            holder.txtSkuName = (TextView) convertView.findViewById(R.id.txtSkuName);
            holder.spnQuantity = (Spinner) convertView.findViewById(R.id.spnQuantity);
            holder.txtPrice = (TextView) convertView.findViewById(R.id.txtPrice);
            holder.txtMarketPrice = (TextView) convertView.findViewById(R.id.txtMarketPrice);
            holder.txtMarketPrice.setPaintFlags(holder.txtMarketPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        UrlImageViewHelper.setUrlDrawable(holder.imgSku, sku.getSmallImage());
        holder.txtSkuName.setText(sku.getName());

        String priceString = context.getString(R.string.full_price_string, AppUtils.getFullPriceString(details.getMarketPrice()));
        holder.txtMarketPrice.setText(priceString);


        final ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_dropdown_item);
        int quantity = Math.min(sku.getAvailableQuantity(), sku.getBuyLimitQuantity());

        if (quantity <= 0) {
            spinnerAdapter.add(context.getString(R.string.out_of_stock));
            holder.spnQuantity.setEnabled(false);
            holder.spnQuantity.setVisibility(View.GONE);
            holder.btnChayhang.setVisibility(View.VISIBLE);


        } else {
            if (sku.getBuyMinQuantity() > 0)
                spinnerAdapter.add("0");
            for (int j = sku.getBuyMinQuantity(); j <= quantity; j++) {
                spinnerAdapter.add("" + j);
            }
            holder.spnQuantity.setVisibility(View.VISIBLE);
            holder.btnChayhang.setVisibility(View.GONE);
            holder.spnQuantity.setEnabled(true);
        }
        holder.spnQuantity.setAdapter(spinnerAdapter);
        spinnerAdapter.notifyDataSetChanged();

        CartItem item = findCartItem(productId, sku.getId());
        if (item != null)
            holder.spnQuantity.setSelection(spinnerAdapter.getPosition("" + item.getQuantity()));
        else
        if (dataSource.size() == 1 && quantity > 0)
            holder.spnQuantity.setSelection(1);
        holder.txtPrice.setText(AppUtils.getFullPriceString(sku.getPrice()) + "đ");

        holder.spnQuantity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                CartItem selected = new CartItem();
                selected.setProductId(productId);
                Integer quantity = AppUtils.tryParse(spinnerAdapter.getItem(position));
                if (quantity != null)
                    selected.setQuantity(quantity);
                selected.setSkuId(sku.getId());
                selected.setExpress(details.isExpressShip());
                selected.setPrice(sku.getPrice());

                selected.setAvailableQuantity(Math.min(sku.getAvailableQuantity(), sku.getBuyLimitQuantity()));
                selected.setMinQuantity(sku.getBuyMinQuantity());
                selected.setSmallImage(sku.getSmallImage());
                selected.setName(sku.getName());

                handler.onCartItemSelected(selected);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });


        return convertView;
    }

    private CartItem findCartItem(int productId, int id) {
        for (CartItem ci : selectedItems) {
            if (ci.getProductId() == productId && ci.getSkuId() == id) {
                return ci;
            }
        }
        return null;
    }
}

